package com.chen.integral.handler;

import com.alibaba.fastjson.JSON;
import com.chen.base.module.base.dto.Response;
import com.chen.base.module.base.util.JWTInfo;
import com.chen.base.module.base.util.StringUtils;
import com.chen.entity.base.login.Admin;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Title: manager-spring-mvc-hb
 * @Description: to do
 * @Author: chenjiwei
 * @Date: 2020-11-26 22:26
 * @Version: 1.0.0
 */
public class AcceptTokenerFilter extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        ServletOutputStream print = null;
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("前置拦截器1 preHandle： 请求的uri为："+requestURL.toString());

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isNullOrEmpty(authorization)) {
            setResponce(response);
            print = response.getOutputStream();
            print.write(JSON.toJSONString(Response.fail("token不能为空")).getBytes());
            return false;
        }

        Response response1 = Tokener.validateJWT(authorization);
        if("10000".equals(response1.getCode())){
            JWTInfo.set((Admin) response1.getData());
            return true;
        }
//        setResponce(response);
//        print = response.getOutputStream();
//        print.write(JSON.toJSONString(response).getBytes());
        setResponce(response);
        print = response.getOutputStream();
        print.write(JSON.toJSONString(response1).getBytes());
        return false;
    }

    private void setResponce(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器1 postHandle： ");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("拦截器1 afterCompletion： ");
    }
}
